import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { User } from "./user.model";
import { Subject } from "rxjs/Subject";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import 'rxjs/add/operator/map';

/**
 * 存储当前用户信息
 */
@Injectable()
export class userService {
    user: User = new User();
    //通过Subject将普通的Observable单路推送转换为多路推送
    public subject: Subject<User> = new Subject<User>();
    public isLogin: boolean = false;
    //获取用户监听
    getUser(): Observable<User> {
        // if(this.subject.asObservable()){
        //     let user1=localStorage.getItem("user");
        //     if(user1){
        //         this.setUser(JSON.parse(user1));
        //         // this.subject.next(JSON.parse(user));  
        //         // this.isLogin=true;
        //     }
        // }
        return this.subject.asObservable();
    }
    //发布用户信息
    setUser(user: User) {
        console.log("发布user");
        console.log(user);
        if(user.id!=null){
            this.isLogin=true;
             localStorage.setItem("user", JSON.stringify(user));
        }else{
            this.isLogin=false;
        }
        this.subject.next(user);
    }
}